﻿using System;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Text.RegularExpressions;

namespace iMade.Model
{

    public class BlogReader : BaseXmlReader, IBlogReader
    {

        const string HTML_TAG_PATTERN = "<.*?>";

        public BlogPostCollection GetBlogPosts(string feedUrl)
        {
            Cache cache = HttpRuntime.Cache;
            string cacheKey = "GetBlogPosts-" + feedUrl;
            if (Configuration.CachingEnabled)
            {
                if (cache[cacheKey] != null)
                {
                    return cache[cacheKey] as BlogPostCollection;
                }
            }

            var collection = new BlogPostCollection();

            try
            {
                var request = WebRequest.Create(feedUrl);
                var response = request.GetResponse();
                var stream = response.GetResponseStream();
                var reader = XmlReader.Create(stream);
                XmlDocument document = new XmlDocument();
                document.Load(reader);
                document.Normalize();

                XmlNodeList itemNodes = document.SelectNodes("/rss/channel/item");

                foreach (XmlNode item in itemNodes)
                {
                    var publishDateStr = GetNodeInnerText(item, "pubDate");
                    var publishDate = DateTime.Parse(publishDateStr).ToLocalTime();
                    var description = GetNodeInnerText(item, "description");
                    var bp = new BlogPost()
                    {
                        Title = GetNodeInnerText(item, "title"),
                        Link = GetNodeInnerText(item, "link"),
                        Summary = ExtractSummary(description),
                        PublishDate = publishDate
                    };
                    // only add recent blog posts
                    if (bp.PublishDate > DateTime.Now.AddMonths(-1))
                    {
                        collection.Add(bp);
                    }
                }
            }
            catch (Exception ex)
            {
                // do nothing
            }

            // sort and limit the results
            var items = collection.OrderBy(bp => bp.PublishDate).Reverse().Take(3);
            collection = new BlogPostCollection(items);

            if (Configuration.CachingEnabled)
            {
                // hold up to 5 minutes
                cache.Insert(cacheKey, collection, null, DateTime.Now.AddMinutes(5),
                    Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }

            return collection;
        }

        private string ExtractSummary(string inputString)
        {
            var str = StripHTML(inputString);
            if (str.Length > 200)
            {
                str = str.Substring(0, 197) + "...";
            }
            return str;
        }

        private string StripHTML(string inputString)
        {
            return Regex.Replace
              (inputString, HTML_TAG_PATTERN, string.Empty);
        }

    }

}
